package com.rw.controller;

import com.rw.pojo.Account;
import com.rw.pojo.User;
import com.rw.service.AccountService;
import com.rw.service.UserService;
import com.rw.utils.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", value = "/apiLogin")
public class LoginServlet extends HttpServlet {
    private UserService userService;
    private AccountService accountService;

    @Override
    public void init() throws ServletException {

        //自定义的监听器实现ApplicationContext的获取
//        ApplicationContext ac = (ApplicationContext) this.getServletContext().getAttribute("ac");
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        this.userService = (UserService) ac.getBean("userService");
        this.accountService = (AccountService) ac.getBean("accountService");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端传过来的参数
        //解决中文乱码问题
        String uname  = new String(request.getParameter("uname").getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
        String pwd = request.getParameter("pwd");
        System.out.println(uname+"----"+ pwd);
        //进行数据查询
        try {
            User user = this.userService.login(uname,pwd);
//            response.setContentType("application/json;charset=utf-8");
            if (user == null){
                    request.getSession().setAttribute("msg","用户用户名或密码错误");
                    response.sendRedirect("./login.jsp");
//                response.getWriter().println("未查询到用户");
            }else {
                System.out.println(user);
                //需要通过用户uid 去查询账户aid
                Account account = this.accountService.getAccountByUid(user.getUid());
                request.getSession().setAttribute("account",account);
                request.getSession().setAttribute("user",user);
                response.sendRedirect("./main.jsp");
//               response.getWriter().println(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //结果返回
    }
}
